package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/pkg/errors"
	"github.com/spf13/cast"
	"net/http"
	"nft-server/common"
	"nft-server/errcode"
	"nft-server/logger"
)

const (
	SuccessCode = 0
	FailedCode  = 1
	SuccessMsg  = "success"
	FailedMsg   = "failed"
)

var successObj = map[string]string{
	"result": "success",
}

// CommonController is a sturct
type CommonController struct {
	beego.Controller
}
type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data,omitempty"`
}

func BuildResponse(obj interface{}) (data *Response) {
	data = &Response{SuccessCode, SuccessMsg, obj}
	return data
}

// HandleBusinessErr is a function
func (ctrl *CommonController) HandleErrCode(errcode errcode.Status) {
	ctrl.Ctx.ResponseWriter.WriteHeader(int(errcode.Code))
	data := &Response{FailedCode, errcode.Message, nil}
	res, err := json.MarshalIndent(data, "", "\t")
	if err != nil {
		logger.Error("HandleErrCode MarshalIndent error: %v", err)
	}
	ctrl.Ctx.ResponseWriter.Write(res)
}

func (ctrl *CommonController) HandleErrCodeAndData(errcode errcode.Status, obj interface{}) {
	ctrl.Ctx.ResponseWriter.WriteHeader(int(errcode.Code))
	data := &Response{FailedCode, errcode.Message, obj}
	res, err := json.MarshalIndent(data, "", "\t")
	if err != nil {
		logger.Error("HandleErrCode MarshalIndent error: %v", err)
	}
	ctrl.Ctx.ResponseWriter.Write(res)
}

// HandleBusinessObj is a function
func (ctrl *CommonController) HandleBusinessObj(obj interface{}) {
	ctrl.Ctx.ResponseWriter.WriteHeader(http.StatusOK)
	data := &Response{SuccessCode, SuccessMsg, obj}
	res, err := json.MarshalIndent(data, "", "\t")
	if err != nil {
		logger.Error("HandleStandObj MarshalIndent error: %v", err)
	}
	ctrl.Ctx.ResponseWriter.Write(res)
}

func (ctrl *CommonController) HandleBusinessSuccess() {
	ctrl.Ctx.ResponseWriter.WriteHeader(http.StatusOK)
	data := &Response{SuccessCode, SuccessMsg, nil}
	res, err := json.MarshalIndent(data, "", "\t")
	if err != nil {
		logger.Error("HandleStandObj MarshalIndent error: %v", err)
	}
	ctrl.Ctx.ResponseWriter.Write(res)
}

// CheckUserIdFromSession 检查session内id和传入id是否一致
func (ctrl *CommonController) CheckUserIdFromSession(userId int) error {
	userInfo := ctrl.GetSession(common.SessionUserId)
	if userInfo == nil {
		err := errors.Errorf("Failed to get userId from session id")
		logger.Error(err.Error())
		return err
	}
	userIdInSession := cast.ToInt(userInfo)
	if userIdInSession != userId {
		err := errors.Errorf("Failed to get userId from session id")
		logger.Error(err.Error())
		return err
	}
	return nil
}
